using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.Product;
using B.S.XZYData.Api.Read.Dto.Product;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Product
{
    /// <summary>
    /// 获取所有产品列表处理器
    /// </summary>
    public class GetAllProductsHandler : IRequestHandler<GetAllProductsCommand, ApiResult<List<ProductDto>>>
    {
        private readonly IBaseRepository<ProductModel> _productRepo;
        private readonly IMapper _mapper;

        public GetAllProductsHandler(
            IBaseRepository<ProductModel> productRepo,
            IMapper mapper)
        {
            _productRepo = productRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<ProductDto>>> Handle(GetAllProductsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<ProductDto>>();

            try
            {
                // 获取所有产品，按产品编号排序
                var products = _productRepo.GetAll()
                    .OrderBy(x => x.Code)
                    .ToList();

                // 映射到 DTO
                var productDtos = _mapper.Map<List<ProductDto>>(products);

                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";
                res.Data = productDtos;
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"查询失败：{ex.Message}";
                res.Data = new List<ProductDto>();
            }

            return res;
        }
    }
} 